/*
 * @Project Name: shoplook
 * @File Name: ApiCustomerImpl
 * @Package Name: com.sm.shoplook.service.customer.impl
 * @Date: 2018/8/14 10:46
 * @Creator: linshixing-1199
 * @line------------------------------
 * @修改人:
 * @修改时间:
 * @修改内容:
 */

package com.sm.shoplook.service.customer.impl;

import java.util.Date;
import java.util.List;

import com.sm.shoplook.dao.mapper.base.SmsRecordMapper;
import com.sm.shoplook.domain.base.SmsRecord;
import com.sm.shoplook.service.system.SmsService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sm.shoplook.constant.ResultMessage;
import com.sm.shoplook.dao.mapper.customer.CustomerMapper;
import com.sm.shoplook.domain.customer.Customer;
import com.sm.shoplook.service.customer.ApiCustomerService;
import com.sm.shoplook.util.JSONUtil;
import com.sm.shoplook.vo.base.ApiException;
import com.sm.shoplook.vo.base.ApiResult;
import com.sm.shoplook.vo.customer.RegCustomerReqVo;

/**
 * @author chenpy
 * @desc 会员-前端接口
 * @date 2018/8/14 10:46
 * @see
 */
@Service
public class ApiCustomerImpl implements ApiCustomerService {

	private static final Logger LOGGER = LoggerFactory.getLogger(ApiCustomerImpl.class);
	@Autowired
	private CustomerMapper customerMapper;
	@Autowired
	private SmsService smsService;
	@Autowired
	private SmsRecordMapper smsRecordMapper;

	/**
	 * @Author chenpy
	 * @Date 2018/8/17 18:33
	 * @Description 会员登录
	 * @param customer
	 * @return
	 */
	@Override
	public ApiResult<String> login(Customer customer) {
		if (StringUtils.isEmpty(customer.getAccount())) {
			return new ApiResult<>(ResultMessage.API_EMAIL_IS_NULL);
		} else if (StringUtils.isEmpty(customer.getPassword())) {
			return new ApiResult<>(ResultMessage.API_PASSWORD_IS_NULL);
		}
		Customer paramCustomer = new Customer();
		paramCustomer.setAccount(customer.getAccount());
		Customer dbCustomer = customerMapper.selectOne(paramCustomer);
		if (null == dbCustomer) {
			return new ApiResult<>(ResultMessage.API_CUSTOMER_NOT_EXISTS);
		}
		if (!customer.getPassword().equals(dbCustomer.getPassword())) {
			return new ApiResult<>(ResultMessage.API_EMAIL_PWD_ERROR);
		}
		// 登录成功，返回标识码
		Customer resultCustomer = new Customer();
		resultCustomer.setId(dbCustomer.getId());
		resultCustomer = customerMapper.selectCustomerCond(resultCustomer);
		return new ApiResult<>(ResultMessage.RESULT_SUCCESS_1, JSONUtil.writeValueAsString(resultCustomer));
	}

	@Override
	public ApiResult<String> insertCustomer(RegCustomerReqVo regCustomerReqVo) throws ApiException {
		if (StringUtils.isEmpty(regCustomerReqVo.getAccount())) {
			return new ApiResult<>(ResultMessage.API_EMAIL_IS_NULL);
		} else if (StringUtils.isEmpty(regCustomerReqVo.getPassword())) {
			return new ApiResult<>(ResultMessage.API_PASSWORD_IS_NULL);
		} else if (!regCustomerReqVo.getPassword().equals(regCustomerReqVo.getConfirmPassword())) {
			return new ApiResult<>(ResultMessage.API_CONFIRM_PWD_NOT_EQUAL);
		}
		Customer paramCustomer = new Customer();
		paramCustomer.setAccount(regCustomerReqVo.getAccount());
		int count = customerMapper.selectCount(paramCustomer);
		if (count > 0) {
			return new ApiResult<>(ResultMessage.API_CUSTOMER_EXISTS);
		}
        ApiResult apiResult = verifySmsCode(regCustomerReqVo.getAccount(), regCustomerReqVo.getAuthCode());
        if (!apiResult.getCode().equals(ResultMessage.RESULT_SUCCESS_1.getCode())) {
            return apiResult;
        }
		Customer customer = new Customer();
		BeanUtils.copyProperties(regCustomerReqVo, customer);
		customer.setCreateTime(new Date());
		int i = customerMapper.insertCustomer(customer);
		if (i < 1) {
			throw new ApiException();
		}
        SmsRecord smsRecord = new SmsRecord();
		smsRecord.setPhoneNum(regCustomerReqVo.getAccount());
		smsRecordMapper.delete(smsRecord);
        Customer resultCustomer = new Customer();
		resultCustomer.setId(customer.getId());
        resultCustomer = customerMapper.selectCustomerCond(resultCustomer);
        return new ApiResult<>(ResultMessage.RESULT_SUCCESS_1, JSONUtil.writeValueAsString(resultCustomer));
	}

	@Override
	public ApiResult<Customer> selectCustomerById(Integer customerId) {
		return new ApiResult<>(ResultMessage.RESULT_SUCCESS_1, customerMapper.selectByPrimaryKey(customerId));
	}

	@Override
	public ApiResult<String> updateCustomer(Customer customer) throws ApiException {
        Customer dbCustomer = customerMapper.selectByPrimaryKey(customer.getId());
        // 如果商户审核失败，则修改为待审核
        if (dbCustomer.getType() == 2 && dbCustomer.getAuditStatus() == 2) {
            customer.setAuditStatus(1);
        }
		int i = customerMapper.updateByPrimaryKeySelective(customer);
		if (i < 1) {
			throw new ApiException();
		}
        // 登录成功，返回标识码
        Customer resultCustomer = new Customer();
        resultCustomer.setId(customer.getId());
        resultCustomer = customerMapper.selectCustomerCond(resultCustomer);
		return new ApiResult<>(ResultMessage.RESULT_SUCCESS_1, JSONUtil.writeValueAsString(resultCustomer));
	}

	@Override
	public ApiResult<Integer> updatePassword(Integer id, String oldPassword, String updNewPassword,
			String updConfirmPassword) throws ApiException {
		Customer dbCustomer = customerMapper.selectByPrimaryKey(id);
		if (null == dbCustomer) {
			return new ApiResult<>(ResultMessage.API_CUSTOMER_NOT_EXISTS);
		}
		if (!dbCustomer.getPassword().equals(oldPassword)) {
			return new ApiResult<>(ResultMessage.API_OLD_PASSWORD_ERROR);
		}
		// 两次密码不一致
		if (!updNewPassword.equals(updConfirmPassword)) {
			return new ApiResult<>(ResultMessage.API_CONFIRM_PWD_NOT_EQUAL);
		}
		Customer customer = new Customer();
		customer.setId(id);
		customer.setPassword(updNewPassword);
		int i = customerMapper.updateByPrimaryKeySelective(customer);
		if (i < 1) {
			throw new ApiException();
		}
		return new ApiResult<>(ResultMessage.RESULT_SUCCESS_1);
	}

	@Override
	public ApiResult<Integer> updateForgetPassword(String account, String password, String confirmPassword,
			String authCode) throws ApiException {
		if (StringUtils.isEmpty(account)) {
			return new ApiResult<>(ResultMessage.API_EMAIL_IS_NULL);
		} else if (StringUtils.isEmpty(password)) {
			return new ApiResult<>(ResultMessage.API_PASSWORD_IS_NULL);
		} else if (!password.equals(confirmPassword)) {
			return new ApiResult<>(ResultMessage.API_CONFIRM_PWD_NOT_EQUAL);
		}
		Customer customer = new Customer();
		customer.setAccount(account);
		customer = customerMapper.selectOne(customer);
		if (customer == null) {
			return new ApiResult<>(ResultMessage.API_CUSTOMER_NOT_EXISTS);
		}
        ApiResult apiResult = verifySmsCode(account, authCode);
		if (!apiResult.getCode().equals(ResultMessage.RESULT_SUCCESS_1.getCode())) {
		    return apiResult;
        }
        customer.setPassword(password);
		customer.setUpdateTime(new Date());
		int i = customerMapper.updateByPrimaryKeySelective(customer);
		if (i < 1) {
			throw new ApiException();
		}
		// 删除验证码
        SmsRecord smsRecord = new SmsRecord();
		smsRecord.setPhoneNum(account);
		smsRecordMapper.delete(smsRecord);
		return new ApiResult<>(ResultMessage.RESULT_SUCCESS_1);
	}

    @Override
    public ApiResult sendSms(String account, Integer type) {
        if (StringUtils.isEmpty(account)) {
            return new ApiResult<>(ResultMessage.API_EMAIL_IS_NULL);
        }
        Customer paramCustomer = new Customer();
        paramCustomer.setAccount(account);
        int count = customerMapper.selectCount(paramCustomer);
        // 账号已存在
        if (count > 0 && type == 1) {
            return new ApiResult<>(ResultMessage.API_CUSTOMER_EXISTS);
        }
        if (count < 1 && type == 2) {
            return new ApiResult<>(ResultMessage.API_CUSTOMER_NOT_EXISTS);
        }
        return smsService.sendSms(account);
    }

    /**
     * 校验验证码
     * @param account 账号
     * @param authCode 验证码
     * @return
     */
    private ApiResult verifySmsCode(String account, String authCode) {
        // 验证码
        SmsRecord paramSmsRecord = new SmsRecord();
        paramSmsRecord.setPhoneNum(account);
        List<SmsRecord> smsRecords = smsRecordMapper.select(paramSmsRecord);
        if (CollectionUtils.isEmpty(smsRecords)) {
            return new ApiResult<>(ResultMessage.API_AUTH_CODE_EXPIRE);
        }
        SmsRecord smsRecord = smsRecords.get(0);
        Date expireTime = smsRecord.getExpireTime();
        // 验证码已过期
        if (expireTime.before(new Date())) {
            // 删除验证码
            smsRecordMapper.delete(smsRecord);
            return new ApiResult<>(ResultMessage.API_AUTH_CODE_EXPIRE);
        }
        if (!smsRecord.getSmsCode().equalsIgnoreCase(authCode)) {
            return new ApiResult<>(ResultMessage.API_AUTH_CODE_ERROR);
        }
        return new ApiResult(ResultMessage.RESULT_SUCCESS_1);
    }
}
